package a66weding.com.jiehuntong.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.common.util.DensityUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import a66weding.com.jiehuntong.R;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/5/18
 * @description :
 */
public class MyRefreshListView extends ListView {

    private View footer;
    private ViewGroup header;
    private LinearLayout headerLay;
    private View newstopview;

    private ImageView imgDown;
    private ImageView imgRefreshing;
    private TextView headText;
    private TextView headTimeText;
    private LinearLayout llay_refresh_view;

    private RelativeLayout bottomRelay;
    private ImageView imgUp;
    private ImageView imgLoading;
    private TextView bottomText;
    private LinearLayout llay_loadmore_view;

    private float listViewOnScreenY = -1;


    // 初始状态
    public static final int INIT = 0;
    // 释放刷新
    public static final int RELEASE_TO_REFRESH = 1;
    // 正在刷新
    public static final int REFRESHING = 2;
    // 释放加载
    public static final int RELEASE_TO_LOAD = 3;
    // 正在加载
    public static final int LOADING = 4;
    // 操作完毕
    public static final int DONE = 5;
    //往上拉的状态
    public static final int PULL = 6;
    //往上拉的状态
    public static final int PULLUP = 7;
    //往下拉的状态
    public static final int PULLDOWN = 8;

    //发延迟消息
    public static final int LOADINGTIME = 9;
    public static final int LOADINGTIME2 = 10;


    // 当前状态
    private int state = INIT;
    // 过滤多点触碰
    private int mEvents;
    private int headerHeight;
    private int topDistance;
    private RotateAnimation upAnimation;
    private RotateAnimation downAnimation;
    private RotateAnimation rotatAnimation;

    private int footerHeight;//底部状态栏的高度

    private OnRefreshingListener onRefreshingListener;
    private int lastVisiblePosition;
    private int distance;
    private boolean isStartY;
    private int paddingdip;

    private boolean isRemark; // 标记是否滑动到底部
    private boolean isPullfresh = false; // 标记是否下拉刷新
    private boolean isFirstTouch;


    public MyRefreshListView(Context context) {
        super(context);
        initHeaderView(context);
        initFooterView(context);
        initAnimation(context);
    }


    public MyRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHeaderView(context);
        initFooterView(context);
        initAnimation(context);
    }

    public MyRefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initHeaderView(context);
        initFooterView(context);
        initAnimation(context);
    }


    private void initHeaderView(Context context) {
        //添加顶部下拉刷新
        header = (ViewGroup) View.inflate(context, R.layout.item_home_headview2, null);
        headerLay = (LinearLayout) header.findViewById(R.id.llay_lsitview_header);
        imgDown = (ImageView) header.findViewById(R.id.iv_listview_header_arrow);
        imgRefreshing = (ImageView) header.findViewById(R.id.pb_listview_header);
        headText = (TextView) header.findViewById(R.id.tv_listview_header_state);
        headTimeText = (TextView) header.findViewById(R.id.tv_listview_header_last_update_time);

        llay_refresh_view = (LinearLayout) header.findViewById(R.id.llay_refreshview);

        llay_refresh_view.measure(0, 0);
        headerHeight = llay_refresh_view.getMeasuredHeight();

        //默认隐藏
        paddingdip = DensityUtil.px2dip(20);
        llay_refresh_view.setPadding(0, -headerHeight, 0, 0);
        CharSequence charSequence = sysTemTimeText();
        headTimeText.setText("最后刷新时间: " + charSequence);

        //       bottomRelay.setPadding(0,0,0,0);//完全显示

        this.addHeaderView(header);

        setOnScrollListener(monScrollListener);

    }


    /**
     * 初始化控件
     */
    private void initFooterView(Context context) {
        //添加底部footer刷新
//        LayoutInflater inflater = LayoutInflater.from(context);
        footer = View.inflate(context, R.layout.footer_refreshlistview, null);
        bottomRelay = (RelativeLayout) footer.findViewById(R.id.rlay_loadmore_view);
        imgUp = (ImageView) footer.findViewById(R.id.iv_pullup_myview);
        imgLoading = (ImageView) footer.findViewById(R.id.iv_loading_myview);
        bottomText = (TextView) footer.findViewById(R.id.tv_loadstate_myview);
        llay_loadmore_view = (LinearLayout) footer.findViewById(R.id.llay_loadmore_view);

        llay_loadmore_view.measure(0, 0);
        footerHeight = llay_loadmore_view.getMeasuredHeight();

        paddingdip = DensityUtil.px2dip(20);
        llay_loadmore_view.setPadding(0, 0, 0, paddingdip);

        this.addFooterView(footer);

        setOnScrollListener(monScrollListener);

    }


    /**
     * 重写onTouchEvent方法，实现头部刷新状态的显示
     */
    int startY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventY = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = eventY;
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isFirstTouch) {
                    startY = eventY;
                    isFirstTouch = true;
                }
                int dY = eventY - startY;
                if (isPullfresh) {//下拉刷新
                    //如果正在加载-联网，不用加载
                    if (state == LOADING) {
                        break;
                    }
                    if (!isStartY) {
                        startY = eventY;
                        isStartY = true;
                    }

                    if (dY > 0 && dY > 20) {//手指往下滑
                        llay_refresh_view.setPadding(0, -headerHeight + dY, 0, 0);
                        if (state != RELEASE_TO_REFRESH) {
                            state = RELEASE_TO_REFRESH;
                            refreshHeaderViewState();
                        }
                    } else {
                        if (state != INIT) {
                            state = INIT;
//                            refreshHeaderViewState();
                            break;
                        }
                    }


                }


                if (isRemark) {//上拉加载
                    //如果正在加载-联网，不用加载
                    if (state == LOADING) {

                        break;
                    }
                    if (!isStartY) {
                        startY = eventY;
                        isStartY = true;
                    }
                    int mathdY = Math.abs(dY);
                    if (dY > 0) {//手指往下滑
                        llay_loadmore_view.setPadding(0, 0, 0, paddingdip);
                        if (state != INIT) {
                            state = INIT;
                            refreshFooterViewState();
                        }
                    } else if (dY < 0) {//手指往上滑
                        if (mathdY > footerHeight) {
                            llay_loadmore_view.setPadding(0, 0, 0, mathdY - footerHeight);
                            if (state != RELEASE_TO_LOAD) {
                                state = RELEASE_TO_LOAD;
                                refreshFooterViewState();
                            }
                        } else if (mathdY < footerHeight) {
                            if (state != INIT) {
                                state = INIT;
                                refreshFooterViewState();
                            }
                        }

                    }

                }

                break;

            case MotionEvent.ACTION_UP:
                isPullfresh = false;


                if (state == RELEASE_TO_REFRESH && state != REFRESHING) {//刷新回到刷新状态
                    llay_refresh_view.setPadding(0, 0, 0, 0);
                    state = REFRESHING;
                    refreshHeaderViewState();
                    //完全显示
                    if (onRefreshingListener != null) {
                        onRefreshingListener.onRefresh();

                    }
                    handler.sendEmptyMessageDelayed(LOADINGTIME, 5000);
                } else if (state == INIT) {
                    //回到初始状态
                    llay_loadmore_view.setPadding(0, 0, 0, paddingdip);
                    llay_refresh_view.setPadding(0, -headerHeight, 0, 0);
                } else if (state == RELEASE_TO_LOAD && state != LOADING) {
                    state = LOADING;
                    //完全显示
                    llay_loadmore_view.setPadding(0, 0, 0, paddingdip);
                    refreshFooterViewState();
                    if (onRefreshingListener != null) {
                        onRefreshingListener.onLoadMore();
                    }
                    handler.sendEmptyMessageDelayed(LOADINGTIME, 5000);
                }


                break;


        }
        return super.onTouchEvent(event);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isPullfresh) {
                    return true;
                }
                break;

        }

        return super.onInterceptTouchEvent(ev);
    }

    /**
     * 更新底部加载更多刷新状态
     */
    private void refreshFooterViewState() {
        switch (state) {
            case INIT://正常状态
                bottomText.setText("上拉加载更多. . .");
                imgUp.startAnimation(downAnimation);
                break;
            case RELEASE_TO_LOAD://释放刷新
                bottomText.setText("释放立即加载");
                imgUp.startAnimation(upAnimation);
                break;
            case LOADING://正在加载
                bottomText.setText("正在加载...");
                imgUp.clearAnimation();
                imgUp.setVisibility(View.GONE);

                imgLoading.setVisibility(View.VISIBLE);

                break;
        }
    }

    /**
     * 更新头部刷新状态
     */
    private void refreshHeaderViewState() {
        switch (state) {
            case INIT://正常状态
                headText.setText("下拉刷新");
                imgRefreshing.setVisibility(GONE);

                break;
            case RELEASE_TO_REFRESH://释放刷新
                headText.setText("释放立即刷新. . .");
                imgRefreshing.setVisibility(GONE);
                imgDown.startAnimation(upAnimation);
                break;
            case REFRESHING://正在加载
                headText.setText("正在加载...");
                imgDown.clearAnimation();
                imgDown.setVisibility(View.GONE);
                imgRefreshing.setVisibility(View.VISIBLE);
                imgRefreshing.startAnimation(rotatAnimation);
                break;

        }
    }


    /**
     * 当刷新完成后，状态复原
     *
     * @param isPullDownRefresh
     */
    public void onRefreshFinish(boolean isPullDownRefresh) {
        if (isPullDownRefresh) {
            headText.setText("加载完成");
            handler.sendEmptyMessageDelayed(LOADINGTIME2, 1500);
        } else {
            bottomText.setText("没有更多数据了...");
            handler.sendEmptyMessageDelayed(LOADINGTIME2, 1500);
        }


    }

    private void resetRefreshState() {
        isPullfresh = false;
        isRemark = false;
        state = INIT;
        //刷新栏复位
        CharSequence charSequence = sysTemTimeText();
        headTimeText.setText("最后刷新时间: " + charSequence);

        llay_refresh_view.setPadding(0, -headerHeight, 0, 0);


        llay_loadmore_view.setPadding(0, 0, 0, paddingdip);
        imgLoading.setVisibility(View.GONE);
        imgUp.setVisibility(View.VISIBLE);
        imgUp.clearAnimation();
    }


    /**
     * ListView的滚动状态监听
     */
    OnScrollListener monScrollListener = new OnScrollListener() {
        /**
         * 静止->滚动
         * 惯性滚动->静止
         * 滚动->惯性滚动
         * @param view
         * @param scrollState
         */
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            lastVisiblePosition = getLastVisiblePosition();
            if (lastVisiblePosition == (getCount() - 1) && scrollState == SCROLL_STATE_IDLE) {
                isRemark = true;
            } else {

            }
        }

        /**
         * 滚动过程中回调的方法
         * @param view
         * @param firstVisibleItem
         * @param visibleItemCount
         * @param totalItemCount
         */
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                             int totalItemCount) {
            if (getLastVisiblePosition() == totalItemCount - 1) {

            } else {
                isRemark = false;
            }
            if (getFirstVisiblePosition() == 0 && visibleItemCount >= 1) {

                if (header.getTop() == 0) {
                    isPullfresh = true;
                }

            } else {
                isPullfresh = false;
            }

            int top = view.getTop();

            int top1 = header.getTop();


            int height = header.getChildAt(1).getHeight();
            boolean isshown = header.getChildAt(1).isShown();

        }
    };

    private CharSequence sysTemTimeText() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeText = simpleDateFormat.format(new Date());
        return timeText;
    }


    /**
     * 刷新箭头旋转动画集
     */
    public void initAnimation(Context context) {
        //向上旋转
        upAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        upAnimation.setDuration(500);
        upAnimation.setFillAfter(true);
        //向下旋转
        downAnimation = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        downAnimation.setDuration(500);
        downAnimation.setFillAfter(true);

        rotatAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        // 添加匀速转动动画
        LinearInterpolator lir = new LinearInterpolator();
        rotatAnimation.setInterpolator(lir);
        rotatAnimation.setRepeatCount(100);
        rotatAnimation.setDuration(1000);
        rotatAnimation.setFillAfter(true);

    }


    public void setOnRefreshingListener(OnRefreshingListener onRefreshing) {
        this.onRefreshingListener = onRefreshing;
    }

    public interface OnRefreshingListener {
        /**
         * 刷新
         */
        public abstract void onRefresh();

        /**
         * 加载更多
         */
        public abstract void onLoadMore();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == LOADINGTIME) {
                onRefreshFinish(false);
            } else if (msg.what == LOADINGTIME2) {
                resetRefreshState();
                bottomText.setText("上拉加载更多");
            }
        }
    };


    public void destoryMsg() {
        handler.removeCallbacksAndMessages(null);
    }


}
